<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="./lib/bootstrap.css" />
  <script src="./lib/jquery.js"></script>
</head>

<body>
  <!-- 1. 文件选择框 -->
  <input type="file" id="file1" />
  <!-- 2. 上传文件的按钮 -->
  <button id="btnUpload">上传文件</button>

  <!-- bootstrap 中的进度条 -->
  <div class="progress" style="width: 500px; margin: 15px 10px;">
    <div class="progress-bar progress-bar-striped active" style="width: 0%" id="percent">
      0%
    </div>
  </div>

  <br />
  <!-- 3. img 标签，来显示上传成功以后的图片 -->
  <img src="" alt="" id="img" width="800" />

  <script>
    // 接口地址： http://www.liulongbin.top:3006/api/upload/avatar

    // 1. 获取到文件上传按钮
    const btnUpload = document.querySelector('#btnUpload')
    const file1 = document.querySelector('#file1')
    // 2. 为按钮绑定单击事件处理函数
    btnUpload.addEventListener('click', function () {
      // 3. 获取到用户选择的文件列表
      console.dir(file1);
      if (file1.files.length <= 0) {
        return alert('请选择文件')
      }
      console.log(file1.files[0])
      const fd = new FormData
      fd.append('active', file1.files[0])
      const xhr = new XMLHttpRequest()
      xhr.open('post', 'http://www.liulongbin.top:3006/api/upload/avatar')

      xhr.upload.onprogress = function(e){
        if(e.lengthComputable){
          const res = Math.ceil(e.loaded/e.total*100)
          console.log(res)
          $('#percent').prop('style',`width : ${res}%`).html(`${res}%`)
        }
      }
      xhr.upload.onload = function(){
        $('#percent').removeClass().addClass('progress-bar progress-bar-success')
      }

      xhr.send(fd)
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          // console.log(JSON.parse(xhr.responseText)) 
          document.querySelector('img').src = `http://www.liulongbin.top:3006${JSON.parse(xhr.responseText).url}`

        }
      }
    })
  </script>
</body>

</html>